<?php

namespace App\Services\TakeUserVipWelfare;

use Carbon\Carbon;
use App\Models\User;
use App\Models\VipWelfare;
use App\Models\VipPurchase;
use App\Models\VipWelfareDetailRelationCoupon;
use Illuminate\Support\Facades\DB;

class TakeUserVipWelfare
{
	protected User $user;

	protected ?Address $address = null;


	public function __construct(User $user)
	{
		$this->user = $user;
	}

	
	protected function validate()
	{

		if (! $this->user->userCanTakeVipPurchaseCount()) {
			fail('用户没有可领取的vip');
			return false;
		} 
		return true;
	}

	protected function takeWelfare()
	{
		return DB::transaction(function () {

           $vipPurchase = $this->user->userCanTakeVipPurchase()->first();
           $welfares = VipWelfare::query()->where('vip_category_id', $vipPurchase->vip_category_id)->get();
           
           foreach($welfares as $welfare){
           		if($welfare->welfareDetails()->count() > 1 ){
           			$this->user->welfares()->create([
           				'welfare_id' => $welfare->id
           			]);
           		}else{
           			if($welfare->welfareDetails()->first()->type == 'coupon' ){

           				$coupons = VipWelfareDetailRelationCoupon::query()
           					->where('vip_welfare_detail_id',$welfare->welfareDetails()->first()->id)
           					->get();
           				foreach($coupons as $coupon){
           					$this->user->coupons()->create([
	           					'welfare_id' => $welfare->id,
	           					'coupon_id' => $coupon->coupon_id,
	           				]);
           				}	
           			}
           		}
           }

       	 $vipPurchase->update(['is_taken'=> true ]);
		});
	}

	public function take()
	{
		if (! $this->validate()) return;
		
		return $this->takeWelfare();
	}
}
